<?php

Yii::import('zii.widgets.CMenu');

/**
 * Class YAdminMenu
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @package backend.widgets
 * @since 1.0
 */
class YAdminMenu extends CMenu
{
	/**
	 * @var array
	 */
	public $htmlOptions = array('class' => 'nav sub-nav');
	/**
	 * @var string
	 */
	public $route;
	/**
	 * @var array
	 */
	public $params;
	/**
	 * @var string
	 */
	public $activeCssClass = 'current';

	/**
	 * @var bool
	 */
	public $collapse = true;

	/**
	 * @var array
	 */
	private $_adminMenuItems = array(
		'control_panel' => array(
			'priority' => 10,
			'label' => '控制面板',
			'icon' => 'dashboard',
			'url' => array('/site/index'),
		),
		'br',
		'content' => array(
			'priority' => 30,
			'label' => '内容',
			'icon' => 'admin-post',
			'url' => array('/content/index'),
			'items' => array(
				array('label' => '管理内容', 'url' => array('/content/index')),
				array('label' => '栏目', 'url' => array('/channel/index')),
				array('label' => '分类', 'url' => array('/taxonomy/index')),
				array('label' => 'Banner', 'url' => array('/banner/index')),
				array('label' => '链接', 'url' => array('/link/index')),
			),
		),
		'media' => array(
			'priority' => 40,
			'label' => '文件',
			'icon' => 'admin-media',
			'url' => array('/file/index'),
			'items' => array(
				array('label' => '已上传的文件', 'url' => array('/file/index')),
				array('label' => '上传', 'url' => array('/file/upload')),
			)
		),
		'user' => array(
			'priority' => 90,
			'label' => '用户',
			'icon' => 'admin-users',
			'url' => array('/user/index'),
			'items' => array(
				array('label' => '所有用户', 'url' => array('/user/index')),
				array('label' => '创建用户', 'url' => array('/user/create')),
				array('label' => '角色', 'url' => array('/role/index')),
				array('label' => '权限', 'url' => array('/permission/index')),
			),
		),
		'setting' => array(
			'priority' => 100,
			'label' => '设置',
			'icon' => 'admin-settings',
			'url' => array('/site/setting', 'category' => 'general'),
			'items' => array(
				array('label' => '常规', 'url' => array('/site/setting', 'category' => 'general')),
			),
		)
	);

	/**
	 * @return array
	 */
	public function getAdminMenuItems()
	{
		return $this->_adminMenuItems;
	}

	/**
	 * @param array $items
	 */
	public function setAdminMenuItems(Array $items)
	{
		$this->_adminMenuItems = array_merge($this->_adminMenuItems, $items);
	}

	/**
	 * 排序
	 *
	 * @param $a
	 * @param $b
	 * @return int
	 */
	public function sort(&$a, &$b)
	{
		if (is_array($a) && isset($a['priority'])) {
			$ap = $a['priority'];
		} else {
			$ap = 0;
		}

		if (is_array($b) && isset($b['priority'])) {
			$bp = $b['priority'];
		} else {
			$bp = 0;
		}

		$result = $ap < $bp ? -1 : 1;

		return $result;
	}

	public function init()
	{
		if (isset(Yii::app()->params['adminMenuItems'])) {
			$adminMenuItems = (array) Yii::app()->params['adminMenuItems'];
			$this->_adminMenuItems = $adminMenuItems;
		}

		$i = 0;
		foreach ($this->_adminMenuItems as $group => $menu) {
			if (is_array($menu) && !isset($menu['priority'])) {
				$this->_adminMenuItems[$group]['priority'] = $i++;
			} elseif (!is_array($menu)) {
				unset($this->_adminMenuItems[$group]);
				$this->_adminMenuItems[(string)$menu] = array('priority' => $i++);
			}
		}
	}

	/**
	 * {@inheritdoc}
	 */
	public function run()
	{
		/** @var CWebApplication $app */
		$app = Yii::app();
		if ($this->route === null && $app->getController() !== null) {
			$this->route = $app->getController()->route;
		}
		if ($this->params === null) {
			$this->params = $_GET;
		}

		uasort($this->_adminMenuItems, array($this, 'sort'));

		$this->_adminMenuItems = $this->filterItems($this->_adminMenuItems);

		$i = 0;
		$count = count($this->_adminMenuItems);
		echo CHtml::openTag('ul', array('class' => 'nav', 'role' => 'navigation'));
		foreach ($this->_adminMenuItems as $group => $menu) {
			if (++$i !== $count && $group === 'br') {
				echo CHtml::closeTag('ul');
				echo CHtml::openTag('ul', array('class' => 'nav', 'role' => 'navigation'));
			} elseif ($group !== 'br') {
				$this->renderTopMenu($menu);
			}
		}
		echo CHtml::closeTag('ul');
		$this->renderCollapse();
	}

	/**
	 * @param array $menu
	 */
	protected function renderTopMenu($menu)
	{
		$class = array('top-menu');
		$isCurrent = false;
		$menuItems = '';

		if (isset($menu['items']) && is_array($menu['items']) && $menu['items']) {
			array_push($class, 'has-sub');
			$items = $this->normalizeItems($menu['items'], $this->route, $isCurrent);
			$items = $this->filterItems($items);
			foreach ($items as $i => $item) {
				if (isset($item['callback'])) {
					$items[$i] = call_user_func($item['callback'], $item);
				}
			}
			ob_start();
			$this->renderMenu($items);
			$menuItems = ob_get_clean();
		} elseif ($this->isItemActive($menu, $this->route)) {
			$isCurrent = true;
		}

		array_push($class, $isCurrent ? 'current-menu' : 'not-current-menu');

		$title = '';
		if (isset($menu['icon'])) {
			$title = '<span class="dashicons dashicons-' . $menu['icon'] . '"></span> ';
		}

		if (isset($menu['callback'])) {
			$menu = call_user_func($menu['callback'], $menu);
		}

		if (!isset($menu['url'])) {
			$menu['url'] = '#';
		}

		$title .= '<span class="menu-name">' . $menu['label'] . '</span>';

		echo strtr('<li class="{class}">{link} {menuItems}</li>', array(
			'{class}' => implode(' ', $class),
			'{link}' => CHtml::link($title, $menu['url']),
			'{menuItems}' => $menuItems,
		));
	}

	protected function renderCollapse()
	{
		if (empty($this->collapse)) {
			return;
		}

		echo <<<EOT
		<button id="collapse-menu" type="button">
		<span class="dashicons dashicons-admin-collapse"></span>
		<span class="collapse-tip">收起菜单</span>
		</button>
EOT;
	}

	/**
	 * 过滤餐单 根据用户权限过滤
	 *
	 * @param $items
	 * @return array
	 */
	protected function filterItems($items)
	{
		/** @var CWebUser $user */
		$user = Yii::app()->getUser();
		if ($user->getId() != User::ROOT_ID) {
			foreach ($items as $index => $item) {
				if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
					$route = str_replace('/index', '', $item['url'][0]);
					if ($route[0] == '/') {
						$route = substr($route, 1);
					}
					if (!$user->checkAccess($route, $_GET)) {
						unset($items[$index]);
					}
					if (isset($item['items'])) {
						$this->filterItems($items);
					}
				}
			}
		}
		return $items;
	}

	/**
	 * @param array $item
	 * @param string $route
	 * @return bool
	 */
	protected function isItemActive($item, $route)
	{
		if (isset($this->getController()->menuRoute)) {
			$menuRoute = $this->getController()->menuRoute;
			if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
				$itemRoute = $item['url'][0];
				if ($itemRoute == $menuRoute) {
					return true;
				}
			}
		}
		return parent::isItemActive($item, $route);
	}
}
